package com.kaede.hayate.common.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * json工具类
 */
public class JsonUtils {
	
	// 定义jackson对象
	//private static final ObjectMapper MAPPER = new ObjectMapper();
	
	//采用单例
	private static class SingletonHolder {  
		    private static final ObjectMapper MAPPER = new ObjectMapper();
	}    
    public static final ObjectMapper getInstance() {
    	return SingletonHolder.MAPPER;  
    } 
	/**
	 * Title: pojoToJson
	 * Description: 将对象转换成json字符串。
	 * @param data
	 * @return
	 */
	public static String objectToJson(Object data) {
		try {
			String string = SingletonHolder.MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将json结果集转化为对象
	 * @param jsonData	json数据
	 * @param beanType		对象中的object类型
	 * @return
	 */
	public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {

		try {
			T t = SingletonHolder.MAPPER.readValue(jsonData, beanType);
			return t;
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}					
		return null;
	}

	/**
	 * 将json结果集转化为对象
	 * @param jsonData	json数据
	 * @param beanType		对象中的object类型
	 * @return
	 */
	public static <T> T jsonToPojo(byte[] jsonData, Class<T> beanType) {

		try {
			T t = SingletonHolder.MAPPER.readValue(jsonData, beanType);
			return t;
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Title: jsonToList
	 * Description:	将json数据转换成pojo对象list
	 * @param jsonData
	 * @param beanType
	 * @return
	 */
	public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {

		JavaType javaType = SingletonHolder.MAPPER.getTypeFactory().constructParametrizedType(ArrayList.class,
				List.class, beanType);
		try {
			List<T> list = SingletonHolder.MAPPER.readValue(jsonData, javaType);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
